<?php


namespace App\Http\Controllers\Backend;

use App\Http\Requests\Company\PaperRequest;
use App\Services\Business\Models\Category;
use App\Services\Business\Models\Paper;
use App\Services\Business\Interfaces\QuestionServiceInterface;
use App\Services\Business\Services\QuestionService;
use App\Services\Company\Interfaces\CompanyServiceInterface;
use App\Services\Company\Services\CompanyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\Business\Interfaces\CompanyCategoryServiceInterface;
use App\Services\Business\Services\CompanyCategoryService;

class PaperController extends BaseController
{
    /**
     * @var  QuestionService
     */
    protected $questionService;

    /**
     * @var  CompanyService
     */
    protected $CompanyService;
    /**
     * @var  CompanyCategoryService
     */
    protected $CompanyCategoryService;


    public function __construct(

        CompanyCategoryServiceInterface $CompanyCategoryService,
        CompanyServiceInterface  $CompanyService,
        QuestionServiceInterface $questionService
    )
    {
        $this->questionService = $questionService;
        $this->CompanyService = $CompanyService;
        $this->CompanyCategoryService = $CompanyCategoryService;


    }

    public function index(Request $request)
    {
        $companyId = $this->loginCompanyId();
        $userId = $request->input('user_id', '');
        $userIds = $request->input('user_ids');
        $excludeIds = $request->input('exclude_ids', []);
        $keywords = $request->input('keywords', '');
        $type = $request->input('type', 0);
        $rating = $request->input('rating', 0);
        $categoryId = $request->input('cid', 0);
        $papers = Paper::query()
            ->when($excludeIds, function ($query) use ($excludeIds) {
                $query->whereNotIn('id', $excludeIds);
            })
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = Category::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($type, function ($query) use ($type) {
                return $query->whereType($type);
            })
            ->when($rating, function ($query) use ($rating) {
                return $query->whereRating($rating);
            })
            ->when($userIds, function ($query) use ($userIds) {
                return $query->whereIn('id', $userIds);
            })
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('company_id', $companyId);
            })
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })

            ->orderByDesc('created_at')
            ->paginate($request->input('size', 10));
        return $this->successData(compact('papers'));
    }


    /**
     * 资源的试卷列表
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public function papers(Request $request, string $type, int $id)
    {
        $size = $request->input('size',10);
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $questions = $resource->papers()->paginate($size);
        return $this->successData(compact('questions'));

    }

    /**
     * 试卷下面的考题
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function questions(Request $request, int $id)
    {
        $size = $request->input('size', 10);
        $paper=  Paper::query()->where('id',$id)->firstOrFail();
        $questions = $paper->questions()->paginate($size);
        return $this->successData(compact('questions'));

    }



    public function storeResourcePaper(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($id)) {
            return $this->error(__('参数错误'));
        }
        $resource->papers()->attach($ids);
        return $this->success(__('绑定试卷成功'));
    }

    public function deleteResourcePaper(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->papers()->detach($ids);
        return $this->success(__('取消试卷成功'));
    }


    public function store(PaperRequest $request, Paper $paper)
    {
        $data = $request->filldata();
        $paper->fill($data)->save();
        return $this->success("插入试卷成功");
    }

    public function  edit($id)
    {
        $companyId= $this->loginCompanyId();
        $paper = Paper::query()->with(['mediaVideo', 'mediaImages'])->where('id',$id)->firstOrFail();
        $mycategories= $this->CompanyCategoryService->tree($companyId);
        return  $this->successData(compact('paper','mycategories'));
    }



    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function deleteQuestion(Request $request, $id)
    {

        $ids = $request->input('ids', []);
        if (!$ids || !$id) {
            return $this->error(__('参数错误'));
        }
        $paper = Paper::query()->where('id', $id)->firstOrFail();
        $paper->questions()->detach($ids);
        $paper->increment('question_count',count($ids));

        return $this->success(__('取绑成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function storeQuestion(Request $request, $id)
    {

        $ids = $request->input('ids', []);
        if (!$ids || !$id) {
            return $this->error(__('参数错误'));
        }
        $paper = Paper::query()->where('id', $id)->firstOrFail();
        $paper->questions()->sync($ids);
        $paper->decrement('question_count', count($ids));

        return $this->success(__('绑定成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id)
    {
        $paper = Paper::query()->where('id', $id)->firstOrFail();
          DB::transaction(function () use ($paper) {
              $paper->questions()->detach();
              $paper->delete();
        });

        return $this->success(__('删除试题成功'));
    }

    /**
     * @param PaperRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(PaperRequest $request, $id)
    {
        $data = $request->filldata();
        DB::transaction(function () use ($id, $data) {
            $paper = Paper::query()->where('id', $id)->firstOrFail();
            $paper->fill($data)->update();
            $paper->mediaImages()->sync($data['images']);
            $paper->mediaVideo()->sync($data['video']);
        });

        return $this->success(__('更新试卷成功'));

    }


    /**
     *
     * 试题排序
     * @param Request $request
     * @return JsonResponse
     */
    public function sort(Request $request)
    {


        $ids = $request->input('ids', []);
// 将 $ids 转换为 ID 到 Sort 值的映射
        $sorts = collect($ids)->mapWithKeys(function ($item) {
            return [$item['id'] => $item['sort']];
        });

// 获取要更新记录的 ID 数组
        $idList = collect($ids)->pluck('id')->toArray();

// 更新操作
        DB::table('paperables')->whereIn('id', $idList)->update(['sort' => DB::raw("(CASE id {$sorts->map(function ($sort, $id) { return "WHEN {$id} THEN {$sort} ";})->implode('')} ELSE sort END)")]);

        return $this->success(__('排序成功'));
    }


}